<template>
  <div class="app-container">
    <!-- 添加或修改在线商品检测记录对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="70%" append-to-body @close="closeModal">
      <!-- 编辑详情图-->
      <div v-if="editType=='0'">
        <image-upload
          ref="uploadDetailsImage"
          key="file-upload-detailsimage"
          v-model="imgList"
          @picture-edit="detailImgEdit"
          @getNonStandardImg="getNonStandardImg"
          :fileSize="3"
          isShowSize
          isEdit
          :isShowNonStandardImgTip="true"
          :isShowImgFormat="true"
          :isShowTip="false"
          :limit="99"/>
      </div>
      <!-- 编辑商品主图 -->
      <div v-else>
        <image-upload
          ref="uploadImage"
          key="file-upload-image"
          v-model="imgList"
          @picture-edit="imageURLsEditFn"
          @getChooseImg="getChooseImg"
          :fileSize="3"
          atlasType="0"
          isLimitsize
          isShowSize
          :isShowChooseImg="true"
          :isShowImgFormat="true"
          isShowRecommend
          :isShowrecommendScale="true"
          :limit="6"/>
        <div style="display: flex" class="mt20">
          <div style="display: flex;flex-direction: column;" class="mr20">
            <el-button class="mb10" size="small" type="success" @click="handleChooseImg('1')">生成白底图</el-button>
            <image-upload v-if="whiteImg" v-model="whiteImg" :isShowTip="false" atlasType="3" :limit="1"
                          isShowSize/>
          </div>
          <div style="display: flex;flex-direction: column;">
            <el-button class="mb10" size="small" type="success" @click="handleChooseImg('0')">生成营销图</el-button>
            <image-upload v-if="marketImg" v-model="marketImg" :isShowTip="false" atlasType="2" :limit="1"
                          isShowSize/>
          </div>
        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button v-if="editType=='0'" type="primary" @click="downloadFile">下载图片到本地</el-button>
        <el-button type="primary" @click="submitImg">确 定</el-button>
        <el-button @click="closeModal">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 图片优化 -->
    <el-dialog :visible.sync="isPictureEdit" title="图片优化" width="1500px" append-to-body destroy-on-close>
      <PictureEditor ref="pictureRef" :key="new Date().getTime()" :data="pictureData" :onCompleted="onCompleted"/>
    </el-dialog>
  </div>
</template>

<script>
import {generateMarketing, generateWhite, saveDetailsImg, saveMarketAndWhite} from "@/api/picture/optimizeTask";
import store from "@/store";
import {pictureEditor} from "@/api/picture/picture";
import {dataURLtoFile} from "@/utils/dataURLtoFile";
import uuid from "@/utils/uuid";
import {bucketUpload} from "@/utils/alioss";
import PictureEditor from '@/components/PictureEditor';
import JSZip from "jszip";
import FileSaver from "file-saver";

export default {
  name: "CollectProductDiagnosisRecord",
  dicts: ['collect_product_diagnosis_status'],
  components: {
    PictureEditor
  },
  props: {
    imageList: {
      type: String,
      default: []
    },
    editType: {
      type: String,
      default: ""
    },
    productId: {
      type: String,
      default: ""
    },
    white: {
      type: String,
      default: ""
    },
    marketing: {
      type: String,
      default: ""
    }
  },
  data() {
    return {
      // 按钮loading
      buttonLoading: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 弹出层标题
      title: this.editType == '0' ? '编辑详情图' : '编辑商品主图',
      // 是否显示弹出层
      open: true,
      imgList: this.imageList.split(';'),
      radioValue: 0,//选择图片下标
      whiteImg: this.white,//白底图
      marketImg: this.marketing,//营销图
      isPictureEdit: false,
      pictureData: {},
      chooseImgUrl: "",//选择的图片地址
    };
  },
  created() {
    console.log('imgList', this.imgList)
  },
  methods: {
    getNonStandardImg(e) {
      // console.log('eee', e)
      this.nonStandardImgList = e
    },
    // 下载文件到本地
    downloadFile() {
      this.$confirm('是否确定下载不规范图片？', '提示').then(() => {
        let list = this.nonStandardImgList
        list.forEach((item, index) => {
          this.getBase64(item).then(res => {
            console.log('res', res)
          })
          return
          const op = dataURLtoFile(this.getBase64(item), uuid() + '.jpg');
          this.handleUpload(op);
        })


        // const zip = new JSZip();
        // const cache = {};
        // const promises = [];
        // // _this.title = "正在加载压缩文件...";
        // let list = this.nonStandardImgList
        // list.forEach((item, index) => {
        //   // console.log('item', item)
        //   const promise = this.getImgArrayBuffer(item).then(data => {
        //     // const file_name = encodeURIComponent(item)
        //     console.log('data', data)
        //     const file_name = index + item.substring(item.lastIndexOf("/") + 1);
        //     // const file_name = 'img' + index
        //     zip.file(file_name, data, {binary: true})
        //     cache[file_name] = data;
        //   })
        //   promises.push(promise);
        //   // window.open(item)
        // })
        // Promise.all(promises).then(() => {
        //   zip.generateAsync({type: "blob"}).then(content => {
        //     FileSaver.saveAs(content, '不规范图片');
        //   })
        // }).catch((err) => {
        //   console.log('err压缩失败', err)
        // })
      })
    },
    // 图片url转base64
    getBase64(imageUrl) {
      return new Promise((resolve, reject) => {
        // 创建新的Image对象并加载图像
        const image = new Image();
        image.crossOrigin = '*'; // 如果需要跨域获取图像数据，则设置此属性
        image.onload = function () {
          const canvas = document.createElement('canvas');
          const context = canvas.getContext('2d');
          // 调整画布大小与图像相同
          canvas.width = image.width;
          canvas.height = image.height;

          // 将图像绘制到画布上
          context.drawImage(image, 0, 0);

          // 从画布中提取图像数据（Base64）
          resolve(canvas.toDataURL());
        };
        image.src = imageUrl;
      });
    },
    // 获取blob文件格式
    getImgArrayBuffer(url) {
      return new Promise((resolve, reject) => {
        //通过请求获取文件blob格式
        let xmlhttp = new XMLHttpRequest();
        console.log('xmlhttp', xmlhttp)
        xmlhttp.open("GET", url);
        xmlhttp.setRequestHeader('Content-Type', 'application/json')
        xmlhttp.responseType = "blob";
        xmlhttp.onreadystatechange = function () {
          console.log('this.status', this.status)
          if (this.status == 200) {
            resolve(this.response);
          } else {
            reject(this.status);
          }
        };
        xmlhttp.send();
      });
    },
    getChooseImg(url) {
      console.log('url', url)
      this.chooseImgUrl = url
    },
    // 选择图片生成白底或营销图
    handleChooseImg(type) {
      let message = type == '1' ? '白底图' : '营销图'
      this.$confirm('是否确定选择此图片作为' + message + '？').then(() => {
        // let imgUrl = this.imgList[this.radioValue]
        let imgUrl = this.chooseImgUrl
        this.$modal.loading('正在生成' + message + '，请稍候...');
        let data = {
          imgUrl: imgUrl.indexOf('http') != -1 ? imgUrl : this.$store.getters.domain + imgUrl
        }
        console.log('data', data.imgUrl)
        if (type == '1') { //生成白底图
          generateWhite(data).then(res => {
            this.$message.success('生成成功')
            this.whiteImg = res.data
          }).finally(() => {
            this.$modal.closeLoading();
          })
        } else { //生成营销图
          generateMarketing(data).then(res => {
            this.$message.success('生成成功')
            this.marketImg = res.data
          }).finally(() => {
            this.$modal.closeLoading();
          })
        }
      })
    },
    onCompleted(data) {//base64格式
      const op = dataURLtoFile(data[0], uuid() + '.jpg');
      this.handleUpload(op);
    },
    // 上传
    handleUpload(op) {
      let bucketName = '' // 桶名
      let dir = `images`
      bucketUpload(op, res => {
          let temp = {
            name: res.attachment,
            url: res.aliyunAddress,
            code: res.code
          }
          const newTwoArr = this.form.detailImg.split(';');
          if (this.editType === '0') {
            const newArr = this.form.imageURLs.split(';');
            newArr[this.isEditIndex] = temp.name
            this.imgList = newArr.join(';');
          } else if (this.editType === '1') {
            const newTwoArr = this.form.detailImg.split(';');
            newTwoArr[this.isEditIndex] = temp.name
            this.imgList = newTwoArr.join(';');
          }
          this.isPictureEdit = false;
        },
        err => {
        },
        bucketName,
        dir
      )
    },
    imageURLsEditFn(item, index) {
      this.isEditIndex = index;
      this.pictureEditorFn(item.url);
    },
    detailImgEdit(item, index) {
      this.isEditIndex = index;
      this.pictureEditorFn(item.url);
    },
    pictureEditorFn(url) {
      this.editLoading = true;
      if (url.indexOf('http://') === -1 && url.indexOf('https://') === -1) url = store.getters.domain + url
      pictureEditor({url: url}).then(res => {
        if (res.code === 200) {
          this.editLoading = false;
          this.isPictureEdit = true;
          this.pictureData = res.data;
          this.$nextTick(() => {
            this.$refs.pictureRef.init();
          })
        }
      }).catch(() => {
        this.editLoading = false;
      })
    },
    // 提交保存图片
    submitImg() {
      console.log('this.imgList.join', this.imgList)
      this.$confirm('是否确定提交？').then(() => {
        this.$modal.loading('正在提交保存中，请稍候...');
        let type = typeof this.imgList
        console.log('type', type)
        if (this.editType == '1') {//修改主图位置
          let data = {
            productId: this.productId,
            imageURLs: type == 'string' ? this.imgList : this.imgList.join(';'),
            type: this.gatherType,
            whiteImg: this.whiteImg,
            marketImg: this.marketImg,
          }
          saveMarketAndWhite(data).then(res => {
            this.$message.success(res.msg)
          }).finally(() => {
            this.$modal.closeLoading();
            this.$emit('close', 'isRef')
          })
        } else {
          let data = {
            detailsImg: type == 'string' ? this.imgList : this.imgList.join(';'),
            productId: this.productId,
          }
          saveDetailsImg(data).then(res => {
            this.$message.success(res.msg)
          }).finally(() => {
            this.$modal.closeLoading();
            this.$emit('close', 'isRef')
          })
        }
      })
    },
    // 取消按钮
    closeModal() {
      this.open = false;
      this.$emit('close', 'isClose')
    }
  }
};
</script>
